﻿using MathTutorPro.Controllers;
using MathTutorPro.Services.Implementations;
using MathTutorPro.Services.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using System.Security.Claims;
using System.Threading.Tasks;

namespace MathTutorPro.Hubs
{
    //[Authorize]
    public class GroupChatHub : Hub
    {
        private readonly IGroupChatService _chatService;
        private readonly ILogger<ClassDetailController> _logger;
        public GroupChatHub(IGroupChatService chatService,
        ILogger<ClassDetailController> logger)
        {
            _chatService = chatService;
            _logger = logger;
        }

        private string GetUserId() => Context.User.FindFirstValue(ClaimTypes.NameIdentifier);

        public async Task SendMessage(int groupId, string content)
        {
            try
            {
                var userId = GetUserId();
                if (string.IsNullOrEmpty(userId))
                {
                    await Clients.Caller.SendAsync("Error", "未登录或登录已过期");
                    return;
                }

                if (string.IsNullOrWhiteSpace(content))
                {
                    await Clients.Caller.SendAsync("Error", "消息内容不能为空");
                    return;
                }

                await _chatService.SendMessageAsync(groupId, userId, content);
                _logger.LogInformation($"用户 {userId} 在群组 {groupId} 发送了消息");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发送消息时发生错误");
                await Clients.Caller.SendAsync("Error", "发送消息失败: " + ex.Message);
            }
        }

        public override async Task OnConnectedAsync()
        {
            try
            {
                var userId = GetUserId();
                if (!string.IsNullOrEmpty(userId))
                {
                    await Groups.AddToGroupAsync(Context.ConnectionId, $"User_{userId}");
                    _logger.LogInformation($"用户 {userId} 已连接，连接ID: {Context.ConnectionId}");
                }
                await base.OnConnectedAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "用户连接时发生错误");
            }
        }

        public override async Task OnDisconnectedAsync(Exception exception)
        {
            try
            {
                var userId = GetUserId();
                if (!string.IsNullOrEmpty(userId))
                {
                    _logger.LogInformation($"用户 {userId} 已断开连接，连接ID: {Context.ConnectionId}");
                }
                await base.OnDisconnectedAsync(exception);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "用户断开连接时发生错误");
            }
        }

        public async Task JoinGroup(int groupId)
        {
            try
            {
                var userId = GetUserId();
                if (string.IsNullOrEmpty(userId))
                {
                    await Clients.Caller.SendAsync("Error", "未登录或登录已过期");
                    return;
                }

                // 这里可以添加组权限验证
                await Groups.AddToGroupAsync(Context.ConnectionId, $"Group_{groupId}");
                _logger.LogInformation($"用户 {userId} 加入群组 {groupId}");
                
                // 通知群组其他成员有新用户加入
                await Clients.Group($"Group_{groupId}").SendAsync("UserJoined", new { 
                    UserId = userId, 
                    GroupId = groupId, 
                    JoinTime = DateTime.Now 
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加入群组时发生错误");
                await Clients.Caller.SendAsync("Error", "加入群组失败: " + ex.Message);
            }
        }

        public async Task LeaveGroup(int groupId)
        {
            try
            {
                var userId = GetUserId();
                if (!string.IsNullOrEmpty(userId))
                {
                    await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"Group_{groupId}");
                    _logger.LogInformation($"用户 {userId} 离开群组 {groupId}");
                    
                    // 通知群组其他成员有用户离开
                    await Clients.Group($"Group_{groupId}").SendAsync("UserLeft", new { 
                        UserId = userId, 
                        GroupId = groupId, 
                        LeaveTime = DateTime.Now 
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "离开群组时发生错误");
            }
        }

        public async Task Typing(int groupId)
        {
            try
            {
                var userId = GetUserId();
                if (!string.IsNullOrEmpty(userId))
                {
                    // 通知群组其他成员有用户正在输入
                    await Clients.Group($"Group_{groupId}").SendAsync("UserTyping", new { 
                        UserId = userId, 
                        GroupId = groupId 
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发送正在输入状态时发生错误");
            }
        }
    }
}
